<template>
  <div class="setting-container">
    <div class="app-container">
      <el-card>
        <el-tabs>
          <!-- 左侧 -->
          <el-tab-pane label="角色管理">
            <!-- 按钮 -->
            <el-button
              icon="el-icon-plus"
              size="small"
              type="primary"
              @click="clickShowAdd"
            >新增角色</el-button>
            <!-- 表格 -->
            <el-table v-loading="loading" :data="list">
              <el-table-column
                label="序号"
                width="100"
                type="index"
                :index="indexMethod"
              />
              <el-table-column label="角色名称" width="240" prop="name" />
              <el-table-column label="描述" prop="description" />
              <el-table-column label="操作">
                <template #default="{row}">
                  <el-button size="small" type="success" @click="clickShowAssignDialog(row.id)">分配权限</el-button>
                  <el-button size="small" type="primary" @click="showEdit(row.id)">编辑</el-button>
                  <el-button size="small" type="danger" @click="delRole(row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-pagination
              :current-page="page"
              :page-sizes="[1, 2, 3, 4,5]"
              :page-size="pagesize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </el-tab-pane>
          <el-dialog :title="showTitle" :visible="showDialog" @close="closeDialog">
            <el-form ref="roleForm" :model="form" :rules="rules" label-width="100px">
              <el-form-item label="角色名称" prop="name">
                <el-input v-model="form.name" placeholder="请输入角色名称" />
              </el-form-item>
              <el-form-item label="角色描述" prop="description">
                <el-input v-model="form.description" placeholder="请输入角色描述" />
              </el-form-item>
            </el-form>

            <template #footer>
              <el-button @click="closeDialog">取消</el-button>
              <el-button type="primary" @click="submitBtn">确认</el-button>
            </template>
          </el-dialog>
          <el-tab-pane label="公司信息">
            <!-- 公司信息 -->
            <!-- 警告信息 -->
            <el-alert
              title="对公司名称、公司地址、营业执照、公司地区的更新，将使得公司资料被重新审核，请谨慎修改"
              type="info"
              show-icon
              :closable="false"
            />
            <!-- 表单 -->
            <el-form label-width="120px" style="margin-top:50px">
              <el-form-item label="公司名称">
                <el-input v-model="companyForm.name" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="公司地址">
                <el-input v-model="companyForm.companyAddress" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="邮箱">
                <el-input v-model="companyForm.mailbox" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="备注">
                <el-input v-model="companyForm.remarks" type="textarea" :rows="3" disabled style="width:400px" />
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>

      </el-card>
    </div>
    <!-- 分配权限的弹层 -->
    <el-dialog title="分配权限" :visible="showAssignDialog" @close="closeAssignDialog" @open="openAssignDialog">
      <el-tree ref="tree" node-key="id" show-checkbox :data="permissionData" :props="{label:'name'}" default-expand-all check-strictly />
      <template #footer>
        <div style="text-align: right;">
          <el-button @click="closeAssignDialog">取消</el-button>
          <el-button type="primary" @click="clickAssign">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { reqAddRole, reqDeleteRole, reqGetRoleList, reqGetRoleDetail, reqUpdateRole, reqAssignPerm } from '@/api/setting'
import { reqGetCompanyById } from '@/api/company'
import { Message } from 'element-ui'
import { reqGetPermissionList } from '@/api/permisson'
import { listToTreeDate } from '@/utils'
export default {
  name: 'Setting',
  data() {
    return {
      loading: false,
      list: [],
      page: 1,
      pagesize: 5,
      total: null,
      showDialog: false,
      form: {
        name: '',
        description: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入角色名称', trigger: ['blur', 'change'] }
        ],
        description: [
          { required: true, message: '请输入角色描述', trigger: ['blur', 'change'] }
        ]
      },
      companyForm: {},
      showAssignDialog: false, // 控制弹层的显示隐藏
      roleId: '', // 记录正在操作的角色
      permissionData: [] // 存储权限数据
    }
  },
  computed: {
    showTitle() {
      return this.form.id ? '编辑角色' : '添加角色'
    }
  },
  created() {
    this.getRoleList()
    this.getCompanyInfo()
  },
  methods: {
    // 获取公司信息
    async getCompanyInfo() {
      const { data } = await reqGetCompanyById(this.$store.state.user.userInfo.companyId)
      this.companyForm = data
    },
    // 编辑角色
    async showEdit(id) {
      const { data } = await reqGetRoleDetail(id)
      console.log(data)
      this.form = data
      this.clickShowAdd()
    },
    // 新增角色功能区域
    // 新增角色
    async submitBtn() {
      try {
        await this.$refs.roleForm.validate()
        if (this.form.id) {
          await reqUpdateRole(this.form)
          // Message.success('编辑成功')
        } else {
          await reqAddRole(this.form)
          // Message.success('新增成功')
        }
        Message.success(`${this.form.id ? '编辑' : '新增'}成功`)
        this.getRoleList()
        this.closeDialog()
      } catch (error) {
        // console.dir(error)
        Message.error(error)
      }
    },
    // 关闭弹窗
    closeDialog() {
      this.showDialog = false
      this.$refs.roleForm.resetFields()
      this.form = {
        name: '',
        description: '' }
    },
    // 打开弹窗
    clickShowAdd() {
      this.showDialog = true
    },
    // 处理序号
    indexMethod(index) {
      return (this.page - 1) * this.pagesize + index + 1
    },
    // 读取公司角色列表
    async getRoleList() {
      this.loading = true
      const { data } = await reqGetRoleList(this.page, this.pagesize)
      this.loading = false
      this.list = data.rows
      this.total = data.total
    },
    // 每页条数改变重新发送请求
    handleSizeChange(val) {
      this.pagesize = val
      this.page = 1
      this.getRoleList()
    },
    // 当前页数改变发送请求
    handleCurrentChange(val) {
      this.page = val
      this.getRoleList()
    },
    // 删除角色 id通过作用域插槽获取
    delRole(id) {
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await reqDeleteRole(id)
        this.$message.success('删除角色成功')
        if (this.list.length === 1 && this.page > 1) {
          this.page--
        }
        this.getRoleList()
      }).catch(() => {
        this.$message.success('取消删除')
      })
    },
    // 关闭弹窗
    closeAssignDialog() {
      this.showAssignDialog = false
    },
    // 打开弹窗，并给角色id赋值
    clickShowAssignDialog(id) {
      this.roleId = id
      this.showAssignDialog = true
    },
    // 打开弹窗发送请求
    async openAssignDialog() {
      const { data } = await reqGetPermissionList()
      // console.log(data)
      this.permissionData = listToTreeDate(data, '0')
      // 发送请求获取权限列表
      const res = await reqGetRoleDetail(this.roleId)
      // console.log(res)
      this.$refs.tree.setCheckedKeys(res.data.permIds)
    },
    // 分配权限
    async clickAssign() {
      // 获取设置号的权限ids数组
      const permIds = this.$refs.tree.getCheckedKeys()
      console.log(permIds)
      // 发送请求，数据为当前角色id和id权限数组
      await reqAssignPerm({
        id: this.roleId,
        permIds
      })
      this.$message.success('权限分配成功')
      this.closeAssignDialog()
    }
  }
}
</script>

<style>

</style>
